{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f7cabbed-cc9e-4d2f-9cee-843c2bc89020",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import math\n",
    "import os\n",
    "import sys\n",
    "import warnings\n",
    "from dataclasses import dataclass, field\n",
    "from itertools import chain\n",
    "from typing import Optional\n",
    "\n",
    "import datasets\n",
    "import evaluate\n",
    "import torch\n",
    "from datasets import load_dataset\n",
    "\n",
    "import transformers\n",
    "from transformers import (\n",
    "    CONFIG_MAPPING,\n",
    "    MODEL_FOR_CAUSAL_LM_MAPPING,\n",
    "    AutoConfig,\n",
    "    AutoModelForCausalLM,\n",
    "    AutoTokenizer,\n",
    "    HfArgumentParser,\n",
    "    Trainer,\n",
    "    TrainingArguments,\n",
    "    default_data_collator,\n",
    "    is_torch_tpu_available,\n",
    "    set_seed,\n",
    ")\n",
    "from transformers.testing_utils import CaptureLogger\n",
    "from transformers.trainer_utils import get_last_checkpoint\n",
    "from transformers.utils import check_min_version, send_example_telemetry\n",
    "from transformers.utils.versions import require_version\n",
    "\n",
    "from flash_attn import flash_attn_qkvpacked_func, flash_attn_func\n",
    "# 改为从ckp加载初始化并用flash attention\n",
    "# 通过 attn_implementation=\"flash_attention_2\" 使用 Flash Attention 2 时，不要将 torch_dtype \n",
    "# 传递给 from_pretrained 类方法并使用自动混合精度训练。使用 Trainer 时，只需将 fp16 或 bf16 指定为 True 。\n",
    "# 否则，请确保您使用的是 torch.autocast 。这是必需的，因为 Flash Attention 仅支持 fp16 和 bf16 数据类型。\n",
    "\n",
    "\n",
    "# 查看minigpt训练代码\n",
    "\n",
    "\n",
    "# train3 把长度设置为512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5f20fc34-544d-4f23-8272-48bb13517d9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Will error if the minimal version of Transformers is not installed. Remove at your own risks.\n",
    "# 用dataclass修饰ModelArguments和DataTrainingArguments，dataclass是数据类，里面的格式就是 变量名：变量值，ModelArguments和DataTrainingArguments\n",
    "# 是模型参数和数据参数，通过命令运行后会改变里面的变量值\n",
    "#check_min_version(\"4.40.0.dev0\")\n",
    "\n",
    "require_version(\"datasets>=1.8.0\", \"To fix: pip install -r examples/pytorch/language-modeling/requirements.txt\")\n",
    "\n",
    "logger = logging.getLogger(__name__)\n",
    "\n",
    "\n",
    "MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())\n",
    "MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class ModelArguments:\n",
    "    \"\"\"\n",
    "    Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.\n",
    "    \"\"\"\n",
    "\n",
    "    model_name_or_path: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"The model checkpoint for weights initialization. Don't set if you want to train a model from scratch.\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    model_type: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\"help\": \"If training from scratch, pass a model type from the list: \" + \", \".join(MODEL_TYPES)},\n",
    "    )\n",
    "    config_overrides: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"Override some existing default config settings when a model is trained from scratch. Example: \"\n",
    "                \"n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    config_name: Optional[str] = field(\n",
    "        default=None, metadata={\"help\": \"Pretrained config name or path if not the same as model_name\"}\n",
    "    )\n",
    "    tokenizer_name: Optional[str] = field(\n",
    "        default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n",
    "    )\n",
    "    cache_dir: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\"help\": \"Where do you want to store the pretrained models downloaded from huggingface.co\"},\n",
    "    )\n",
    "    use_fast_tokenizer: bool = field(\n",
    "        default=True,\n",
    "        metadata={\"help\": \"Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.\"},\n",
    "    )\n",
    "    model_revision: str = field(\n",
    "        default=\"main\",\n",
    "        metadata={\"help\": \"The specific model version to use (can be a branch name, tag name or commit id).\"},\n",
    "    )\n",
    "    token: str = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"The token to use as HTTP bearer authorization for remote files. If not specified, will use the token \"\n",
    "                \"generated when running `huggingface-cli login` (stored in `~/.huggingface`).\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    use_auth_token: bool = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": \"The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.\"\n",
    "        },\n",
    "    )\n",
    "    trust_remote_code: bool = field(\n",
    "        default=False,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"Whether or not to allow for custom models defined on the Hub in their own modeling files. This option \"\n",
    "                \"should only be set to `True` for repositories you trust and in which you have read the code, as it will \"\n",
    "                \"execute code present on the Hub on your local machine.\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    torch_dtype: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the \"\n",
    "                \"dtype will be automatically derived from the model's weights.\"\n",
    "            ),\n",
    "            \"choices\": [\"auto\", \"bfloat16\", \"float16\", \"float32\"],\n",
    "        },\n",
    "    )\n",
    "    low_cpu_mem_usage: bool = field(\n",
    "        default=False,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. \"\n",
    "                \"set True will benefit LLM loading time and RAM consumption.\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "\n",
    "    def __post_init__(self):\n",
    "        if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):\n",
    "            raise ValueError(\n",
    "                \"--config_overrides can't be used in combination with --config_name or --model_name_or_path\"\n",
    "            )\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class DataTrainingArguments:\n",
    "    \"\"\"\n",
    "    Arguments pertaining to what data we are going to input our model for training and eval.\n",
    "    \"\"\"\n",
    "\n",
    "    dataset_name: Optional[str] = field(\n",
    "        default=None, metadata={\"help\": \"The name of the dataset to use (via the datasets library).\"}\n",
    "    )\n",
    "    dataset_config_name: Optional[str] = field(\n",
    "        default=None, metadata={\"help\": \"The configuration name of the dataset to use (via the datasets library).\"}\n",
    "    )\n",
    "    train_file: Optional[str] = field(default=None, metadata={\"help\": \"The input training data file (a text file).\"})\n",
    "    validation_file: Optional[str] = field(\n",
    "        default=None,\n",
    "        metadata={\"help\": \"An optional input evaluation data file to evaluate the perplexity on (a text file).\"},\n",
    "    )\n",
    "    max_train_samples: Optional[int] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"For debugging purposes or quicker training, truncate the number of training examples to this \"\n",
    "                \"value if set.\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    max_eval_samples: Optional[int] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"For debugging purposes or quicker training, truncate the number of evaluation examples to this \"\n",
    "                \"value if set.\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    streaming: bool = field(default=False, metadata={\"help\": \"Enable streaming mode\"})\n",
    "    block_size: Optional[int] = field(\n",
    "        default=None,\n",
    "        metadata={\n",
    "            \"help\": (\n",
    "                \"Optional input sequence length after tokenization. \"\n",
    "                \"The training dataset will be truncated in block of this size for training. \"\n",
    "                \"Default to the model max input length for single sentence inputs (take into account special tokens).\"\n",
    "            )\n",
    "        },\n",
    "    )\n",
    "    overwrite_cache: bool = field(\n",
    "        default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"}\n",
    "    )\n",
    "    validation_split_percentage: Optional[int] = field(\n",
    "        default=5,\n",
    "        metadata={\n",
    "            \"help\": \"The percentage of the train set used as validation set in case there's no validation split\"\n",
    "        },\n",
    "    )\n",
    "    preprocessing_num_workers: Optional[int] = field(\n",
    "        default=None,\n",
    "        metadata={\"help\": \"The number of processes to use for the preprocessing.\"},\n",
    "    )\n",
    "    keep_linebreaks: bool = field(\n",
    "        default=True, metadata={\"help\": \"Whether to keep line breaks when using TXT files or not.\"}\n",
    "    )\n",
    "    use_tokenizer_data: bool = field(\n",
    "        default=False, metadata={\"help\": \"use_tokenizer_data\"}\n",
    "    )\n",
    "    tokenizer_datasets: Optional[str] = field(\n",
    "        default=None, metadata={\"help\": \"tokenizer_datasets\"}\n",
    "    )\n",
    "    \n",
    "    def __post_init__(self):\n",
    "        if self.streaming:\n",
    "            require_version(\"datasets>=2.0.0\", \"The streaming feature requires `datasets>=2.0.0`\")\n",
    "\n",
    "        if self.dataset_name is None and self.train_file is None and self.validation_file is None:\n",
    "            raise ValueError(\"Need either a dataset name or a training/validation file.\")\n",
    "        else:\n",
    "            if self.train_file is not None:\n",
    "                extension = self.train_file.split(\".\")[-1]\n",
    "                assert extension in [\"csv\", \"json\", \"txt\"], \"`train_file` should be a csv, a json or a txt file.\"\n",
    "            if self.validation_file is not None:\n",
    "                extension = self.validation_file.split(\".\")[-1]\n",
    "                assert extension in [\"csv\", \"json\", \"txt\"], \"`validation_file` should be a csv, a json or a txt file.\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ec922b35",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # 模拟命令行运行，传入必要的的参数\n",
    "# from sys import argv\n",
    "# argv=['run_clm_copy.py', '--config_name', '/root/model/Qwen/Qwen1.5-1.8B', '--train_file', '/root/data/m-a-p/zh_baike.json', '--tokenizer_name', '/root/model/Qwen/Qwen1.5-1.8B','--per_device_train_batch_size', '8', '--per_device_eval_batch_size', '8', '--do_train', '--do_eval', '--output_dir', '/tmp/test-clm']\n",
    "# print(len(argv))\n",
    "# print(argv)\n",
    "# sys.argv=argv\n",
    "# \"fp16\" :true,\n",
    "sys.argv=['run_clm_copy.py','/root/code/pre-train/args3.json']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d3173126",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 接受传入的参数，\n",
    "parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))\n",
    "if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n",
    "    # If we pass only one argument to the script and it's the path to a json file,\n",
    "    # let's parse it to get our arguments.\n",
    "    model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]), allow_extra_keys=True)\n",
    "else:\n",
    "    model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n",
    "\n",
    "if model_args.use_auth_token is not None:\n",
    "    warnings.warn(\n",
    "        \"The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.\",\n",
    "        FutureWarning,\n",
    "    )\n",
    "    if model_args.token is not None:\n",
    "        raise ValueError(\"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\")\n",
    "    model_args.token = model_args.use_auth_token\n",
    "\n",
    "# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The\n",
    "# information sent is the one passed as arguments along with your Python/PyTorch versions.\n",
    "# send_example_telemetry(\"run_clm\", model_args, data_args)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3ffebabf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:16:26 - WARNING - __main__ - Process rank: 0, device: cuda:0, n_gpu: 1, distributed training: False, 16-bits training: False\n",
      "04/21/2024 17:16:26 - INFO - __main__ - Training/evaluation parameters TrainingArguments(\n",
      "_n_gpu=1,\n",
      "accelerator_config={'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'gradient_accumulation_kwargs': None},\n",
      "adafactor=False,\n",
      "adam_beta1=0.9,\n",
      "adam_beta2=0.999,\n",
      "adam_epsilon=1e-08,\n",
      "auto_find_batch_size=False,\n",
      "bf16=True,\n",
      "bf16_full_eval=False,\n",
      "data_seed=None,\n",
      "dataloader_drop_last=False,\n",
      "dataloader_num_workers=0,\n",
      "dataloader_persistent_workers=False,\n",
      "dataloader_pin_memory=True,\n",
      "dataloader_prefetch_factor=None,\n",
      "ddp_backend=None,\n",
      "ddp_broadcast_buffers=None,\n",
      "ddp_bucket_cap_mb=None,\n",
      "ddp_find_unused_parameters=None,\n",
      "ddp_timeout=1800,\n",
      "debug=[],\n",
      "deepspeed=None,\n",
      "disable_tqdm=False,\n",
      "dispatch_batches=None,\n",
      "do_eval=False,\n",
      "do_predict=False,\n",
      "do_train=True,\n",
      "eval_accumulation_steps=None,\n",
      "eval_delay=0,\n",
      "eval_steps=None,\n",
      "evaluation_strategy=no,\n",
      "fp16=False,\n",
      "fp16_backend=auto,\n",
      "fp16_full_eval=False,\n",
      "fp16_opt_level=O1,\n",
      "fsdp=[],\n",
      "fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False},\n",
      "fsdp_min_num_params=0,\n",
      "fsdp_transformer_layer_cls_to_wrap=None,\n",
      "full_determinism=False,\n",
      "gradient_accumulation_steps=1,\n",
      "gradient_checkpointing=False,\n",
      "gradient_checkpointing_kwargs=None,\n",
      "greater_is_better=None,\n",
      "group_by_length=False,\n",
      "half_precision_backend=auto,\n",
      "hub_always_push=False,\n",
      "hub_model_id=None,\n",
      "hub_private_repo=False,\n",
      "hub_strategy=every_save,\n",
      "hub_token=<HUB_TOKEN>,\n",
      "ignore_data_skip=False,\n",
      "include_inputs_for_metrics=False,\n",
      "include_num_input_tokens_seen=False,\n",
      "include_tokens_per_second=False,\n",
      "jit_mode_eval=False,\n",
      "label_names=None,\n",
      "label_smoothing_factor=0.0,\n",
      "learning_rate=5e-05,\n",
      "length_column_name=length,\n",
      "load_best_model_at_end=False,\n",
      "local_rank=0,\n",
      "log_level=passive,\n",
      "log_level_replica=warning,\n",
      "log_on_each_node=True,\n",
      "logging_dir=/root/tmp/Train2/runs/Apr21_17-16-25_intern-studio-069750,\n",
      "logging_first_step=False,\n",
      "logging_nan_inf_filter=True,\n",
      "logging_steps=500,\n",
      "logging_strategy=steps,\n",
      "lr_scheduler_kwargs={},\n",
      "lr_scheduler_type=linear,\n",
      "max_grad_norm=1.0,\n",
      "max_steps=-1,\n",
      "metric_for_best_model=None,\n",
      "mp_parameters=,\n",
      "neftune_noise_alpha=None,\n",
      "no_cuda=False,\n",
      "num_train_epochs=1,\n",
      "optim=adamw_torch,\n",
      "optim_args=None,\n",
      "optim_target_modules=None,\n",
      "output_dir=/root/tmp/Train2,\n",
      "overwrite_output_dir=True,\n",
      "past_index=-1,\n",
      "per_device_eval_batch_size=1,\n",
      "per_device_train_batch_size=1,\n",
      "prediction_loss_only=False,\n",
      "push_to_hub=False,\n",
      "push_to_hub_model_id=None,\n",
      "push_to_hub_organization=None,\n",
      "push_to_hub_token=<PUSH_TO_HUB_TOKEN>,\n",
      "ray_scope=last,\n",
      "remove_unused_columns=True,\n",
      "report_to=['tensorboard'],\n",
      "resume_from_checkpoint=None,\n",
      "run_name=/root/tmp/Train2,\n",
      "save_on_each_node=False,\n",
      "save_only_model=False,\n",
      "save_safetensors=True,\n",
      "save_steps=6000,\n",
      "save_strategy=steps,\n",
      "save_total_limit=5,\n",
      "seed=42,\n",
      "skip_memory_metrics=True,\n",
      "split_batches=None,\n",
      "tf32=None,\n",
      "torch_compile=False,\n",
      "torch_compile_backend=None,\n",
      "torch_compile_mode=None,\n",
      "torchdynamo=None,\n",
      "tpu_metrics_debug=False,\n",
      "tpu_num_cores=None,\n",
      "use_cpu=False,\n",
      "use_ipex=False,\n",
      "use_legacy_prediction_loop=False,\n",
      "use_mps_device=False,\n",
      "warmup_ratio=0.0,\n",
      "warmup_steps=0,\n",
      "weight_decay=0.0,\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "# 设置logging和检查上一次的CKPT\n",
    "# Setup logging\n",
    "logging.basicConfig(\n",
    "    format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n",
    "    datefmt=\"%m/%d/%Y %H:%M:%S\",\n",
    "    handlers=[logging.StreamHandler(sys.stdout)],\n",
    ")\n",
    "\n",
    "if training_args.should_log:\n",
    "    # The default of training_args.log_level is passive, so we set log level at info here to have that default.\n",
    "    transformers.utils.logging.set_verbosity_info()\n",
    "\n",
    "log_level = training_args.get_process_log_level()\n",
    "logger.setLevel(log_level)\n",
    "datasets.utils.logging.set_verbosity(log_level)\n",
    "transformers.utils.logging.set_verbosity(log_level)\n",
    "transformers.utils.logging.enable_default_handler()\n",
    "transformers.utils.logging.enable_explicit_format()\n",
    "\n",
    "# Log on each process the small summary:\n",
    "logger.warning(\n",
    "    f\"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, \"\n",
    "    + f\"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}\"\n",
    ")\n",
    "logger.info(f\"Training/evaluation parameters {training_args}\")\n",
    "\n",
    "# Detecting last checkpoint.\n",
    "last_checkpoint = None\n",
    "if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:\n",
    "    last_checkpoint = get_last_checkpoint(training_args.output_dir)\n",
    "    if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:\n",
    "        raise ValueError(\n",
    "            f\"Output directory ({training_args.output_dir}) already exists and is not empty. \"\n",
    "            \"Use --overwrite_output_dir to overcome.\"\n",
    "        )\n",
    "    elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:\n",
    "        logger.info(\n",
    "            f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change \"\n",
    "            \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\"\n",
    "        )\n",
    "\n",
    "# Set seed before initializing model.\n",
    "set_seed(training_args.seed)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ec001b40",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DataTrainingArguments(dataset_name=None, dataset_config_name=None, train_file='/root/data/m-a-p/zh_baike.json', validation_file=None, max_train_samples=None, max_eval_samples=None, streaming=False, block_size=None, overwrite_cache=False, validation_split_percentage=5, preprocessing_num_workers=None, keep_linebreaks=True, use_tokenizer_data=False, tokenizer_datasets='/root/data/m-a-p/lm_datasets_8k')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_args"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "399c3d28",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:06 - INFO - datasets.builder - Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:06 - INFO - datasets.info - Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Generating dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:07 - INFO - datasets.builder - Generating dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:07 - INFO - datasets.builder - Downloading and preparing dataset json/default to /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading took 0.0 min\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:07 - INFO - datasets.download.download_manager - Downloading took 0.0 min\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Checksum Computation took 0.0 min\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:07 - INFO - datasets.download.download_manager - Checksum Computation took 0.0 min\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Generating train split\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:07 - INFO - datasets.builder - Generating train split\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Generating train split: 3040159 examples [00:47, 63612.36 examples/s]\n",
      "Unable to verify splits sizes.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:55 - INFO - datasets.utils.info_utils - Unable to verify splits sizes.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05. Subsequent calls will reuse this data.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:55 - INFO - datasets.builder - Dataset json downloaded and prepared to /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05. Subsequent calls will reuse this data.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Overwrite dataset info from restored data version if exists.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Overwrite dataset info from restored data version if exists.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Found cached dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Using custom data configuration default-6e304f38e30a2991\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset Infos from /root/.conda/envs/meta/lib/python3.10/site-packages/datasets/packaged_modules/json\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Overwrite dataset info from restored data version if exists.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Overwrite dataset info from restored data version if exists.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.builder - Found cached dataset json (/root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "04/21/2024 17:18:57 - INFO - datasets.info - Loading Dataset info from /root/.cache/huggingface/datasets/json/default-6e304f38e30a2991/0.0.0/ab573428e7a11a7e23eebd41a2a71665ac3789ce311cbad7049572034a9bda05\n"
     ]
    }
   ],
   "source": [
    "if not data_args.use_tokenizer_data:\n",
    "    # 加载数据\n",
    "    # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)\n",
    "    # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/\n",
    "    # (the dataset will be downloaded automatically from the datasets Hub).\n",
    "    #\n",
    "    # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called\n",
    "    # 'text' is found. You can easily tweak this behavior (see below).\n",
    "    #\n",
    "    # In distributed training, the load_dataset function guarantee that only one local process can concurrently\n",
    "    # download the dataset.\n",
    "    if data_args.dataset_name is not None:\n",
    "        # Downloading and loading a dataset from the hub.\n",
    "        raw_datasets = load_dataset(\n",
    "            data_args.dataset_name,\n",
    "            data_args.dataset_config_name,\n",
    "            cache_dir=model_args.cache_dir,\n",
    "            token=model_args.token,\n",
    "            streaming=data_args.streaming,\n",
    "        )\n",
    "        if \"validation\" not in raw_datasets.keys():\n",
    "            raw_datasets[\"validation\"] = load_dataset(\n",
    "                data_args.dataset_name,\n",
    "                data_args.dataset_config_name,\n",
    "                split=f\"train[:{data_args.validation_split_percentage}%]\",\n",
    "                cache_dir=model_args.cache_dir,\n",
    "                token=model_args.token,\n",
    "                streaming=data_args.streaming,\n",
    "            )\n",
    "            raw_datasets[\"train\"] = load_dataset(\n",
    "                data_args.dataset_name,\n",
    "                data_args.dataset_config_name,\n",
    "                split=f\"train[{data_args.validation_split_percentage}%:]\",\n",
    "                cache_dir=model_args.cache_dir,\n",
    "                token=model_args.token,\n",
    "                streaming=data_args.streaming,\n",
    "            )\n",
    "    else:\n",
    "        data_files = {}\n",
    "        dataset_args = {}\n",
    "        if data_args.train_file is not None:\n",
    "            data_files[\"train\"] = data_args.train_file\n",
    "        if data_args.validation_file is not None:\n",
    "            data_files[\"validation\"] = data_args.validation_file\n",
    "        extension = (\n",
    "            data_args.train_file.split(\".\")[-1]\n",
    "            if data_args.train_file is not None\n",
    "            else data_args.validation_file.split(\".\")[-1]\n",
    "        )\n",
    "        if extension == \"txt\":\n",
    "            extension = \"text\"\n",
    "            dataset_args[\"keep_linebreaks\"] = data_args.keep_linebreaks\n",
    "        raw_datasets = load_dataset(\n",
    "            extension,\n",
    "            data_files=data_files,\n",
    "            cache_dir=model_args.cache_dir,\n",
    "            token=model_args.token,\n",
    "            **dataset_args,\n",
    "        )\n",
    "        # If no validation data is there, validation_split_percentage will be used to divide the dataset.\n",
    "        if \"validation\" not in raw_datasets.keys():\n",
    "            raw_datasets[\"validation\"] = load_dataset(\n",
    "                extension,\n",
    "                data_files=data_files,\n",
    "                split=f\"train[:{data_args.validation_split_percentage}%]\",\n",
    "                cache_dir=model_args.cache_dir,\n",
    "                token=model_args.token,\n",
    "                **dataset_args,\n",
    "            )\n",
    "            raw_datasets[\"train\"] = load_dataset(\n",
    "                extension,\n",
    "                data_files=data_files,\n",
    "                split=f\"train[{data_args.validation_split_percentage}%:]\",\n",
    "                cache_dir=model_args.cache_dir,\n",
    "                token=model_args.token,\n",
    "                **dataset_args,\n",
    "            )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "63c57035",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    train: Dataset({\n",
       "        features: ['text'],\n",
       "        num_rows: 2888151\n",
       "    })\n",
       "    validation: Dataset({\n",
       "        features: ['text'],\n",
       "        num_rows: 152008\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
      "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
      "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
      "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
     ]
    }
   ],
   "source": [
    "raw_datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb8bb3a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过config加载模型 和 Tokenizer\n",
    "# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at\n",
    "# https://huggingface.co/docs/datasets/loading_datasets.\n",
    "\n",
    "# Load pretrained model and tokenizer\n",
    "#\n",
    "# Distributed training:\n",
    "# The .from_pretrained methods guarantee that only one local process can concurrently\n",
    "# download model & vocab.\n",
    "\n",
    "config_kwargs = {\n",
    "    \"cache_dir\": model_args.cache_dir,\n",
    "    \"revision\": model_args.model_revision,\n",
    "    \"token\": model_args.token,\n",
    "    \"trust_remote_code\": model_args.trust_remote_code\n",
    "}\n",
    "# \"hidden_size\":512,\n",
    "# \"kv_channels\":64,\n",
    "# \"num_attention_heads\":8,\n",
    "# \"num_hidden_layers\":8,\n",
    "# \"bf16\":True\n",
    "if model_args.config_name:\n",
    "    config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)\n",
    "elif model_args.model_name_or_path:\n",
    "    config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)\n",
    "else:\n",
    "    config = CONFIG_MAPPING[model_args.model_type]()\n",
    "    logger.warning(\"You are instantiating a new config instance from scratch.\")\n",
    "    if model_args.config_overrides is not None:\n",
    "        logger.info(f\"Overriding config: {model_args.config_overrides}\")\n",
    "        config.update_from_string(model_args.config_overrides)\n",
    "        logger.info(f\"New config: {config}\")\n",
    "\n",
    "tokenizer_kwargs = {\n",
    "    \"cache_dir\": model_args.cache_dir,\n",
    "    \"use_fast\": model_args.use_fast_tokenizer,\n",
    "    \"revision\": model_args.model_revision,\n",
    "    \"token\": model_args.token,\n",
    "    \"trust_remote_code\": model_args.trust_remote_code,\n",
    "}\n",
    "if model_args.tokenizer_name:\n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)\n",
    "elif model_args.model_name_or_path:\n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)\n",
    "else:\n",
    "    raise ValueError(\n",
    "        \"You are instantiating a new tokenizer from scratch. This is not supported by this script. \"\n",
    "        \"You can do it from another script, save it, and load it from here, using --tokenizer_name.\"\n",
    "    )\n",
    "config\n",
    "\n",
    "if model_args.model_name_or_path:\n",
    "    torch_dtype = (\n",
    "        model_args.torch_dtype\n",
    "        if model_args.torch_dtype in [\"auto\", None]\n",
    "        else getattr(torch, model_args.torch_dtype)\n",
    "    )\n",
    "    model = AutoModelForCausalLM.from_pretrained(\n",
    "        model_args.model_name_or_path,\n",
    "        from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n",
    "        config=config,\n",
    "        cache_dir=model_args.cache_dir,\n",
    "        revision=model_args.model_revision,\n",
    "        token=model_args.token,\n",
    "        trust_remote_code=model_args.trust_remote_code,\n",
    "        torch_dtype=torch_dtype,\n",
    "        low_cpu_mem_usage=model_args.low_cpu_mem_usage,\n",
    "        attn_implementation=\"flash_attention_2\"\n",
    "    )\n",
    "else:\n",
    "    model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)\n",
    "    n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())\n",
    "    logger.info(f\"Training new model from scratch - Total size={n_params/2**20:.2f}M params\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4fa1e2ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "if not data_args.use_tokenizer_data:\n",
    "    # 把datasets tokenizer了 block_size > max_pos_embeddings\n",
    "    # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch\n",
    "    # on a small vocab and want a smaller embedding size, remove this test.\n",
    "    embedding_size = model.get_input_embeddings().weight.shape[0]\n",
    "    if len(tokenizer) > embedding_size:\n",
    "        model.resize_token_embeddings(len(tokenizer))\n",
    "\n",
    "    # Preprocessing the datasets.\n",
    "    # First we tokenize all the texts.\n",
    "    if training_args.do_train:\n",
    "        column_names = list(raw_datasets[\"train\"].features)\n",
    "    else:\n",
    "        column_names = list(raw_datasets[\"validation\"].features)\n",
    "    text_column_name = \"text\" if \"text\" in column_names else column_names[0]\n",
    "\n",
    "    # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function\n",
    "    tok_logger = transformers.utils.logging.get_logger(\"transformers.tokenization_utils_base\")\n",
    "\n",
    "    def tokenize_function(examples):\n",
    "        with CaptureLogger(tok_logger) as cl:\n",
    "            output = tokenizer(examples[text_column_name])\n",
    "        # clm input could be much much longer than block_size\n",
    "        if \"Token indices sequence length is longer than the\" in cl.out:\n",
    "            tok_logger.warning(\n",
    "                \"^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits\"\n",
    "                \" before being passed to the model.\"\n",
    "            )\n",
    "        return output\n",
    "\n",
    "    with training_args.main_process_first(desc=\"dataset map tokenization\"):\n",
    "        if not data_args.streaming:\n",
    "            tokenized_datasets = raw_datasets.map(\n",
    "                tokenize_function,\n",
    "                batched=True,\n",
    "                num_proc=data_args.preprocessing_num_workers,\n",
    "                remove_columns=column_names,\n",
    "                load_from_cache_file=not data_args.overwrite_cache,\n",
    "                desc=\"Running tokenizer on dataset\",\n",
    "            )\n",
    "        else:\n",
    "            tokenized_datasets = raw_datasets.map(\n",
    "                tokenize_function,\n",
    "                batched=True,\n",
    "                remove_columns=column_names,\n",
    "            )\n",
    "    if hasattr(config, \"max_position_embeddings\"):\n",
    "        max_pos_embeddings = config.max_position_embeddings\n",
    "    else:\n",
    "        # Define a default value if the attribute is missing in the config.\n",
    "        max_pos_embeddings = 1024\n",
    "\n",
    "    if data_args.block_size is None:\n",
    "        block_size = tokenizer.model_max_length\n",
    "        if block_size > max_pos_embeddings:\n",
    "            logger.warning(\n",
    "                f\"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). \"\n",
    "                f\"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx.\"\n",
    "            )\n",
    "            if max_pos_embeddings > 0:\n",
    "                block_size = min(1024, max_pos_embeddings)\n",
    "            else:\n",
    "                block_size = 1024\n",
    "    else:\n",
    "        if data_args.block_size > tokenizer.model_max_length:\n",
    "            logger.warning(\n",
    "                f\"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model \"\n",
    "                f\"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}.\"\n",
    "            )\n",
    "        block_size = min(data_args.block_size, tokenizer.model_max_length)\n",
    "    tokenized_datasets.save_to_disk('/root/data/m-a-p/tokenized_datasets_8K')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3860b02b",
   "metadata": {},
   "outputs": [],
   "source": [
    "if not data_args.use_tokenizer_data:\n",
    "    # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.\n",
    "    def group_texts(examples):\n",
    "        # Concatenate all texts.\n",
    "        concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}\n",
    "        total_length = len(concatenated_examples[list(examples.keys())[0]])\n",
    "        # We drop the small remainder, and if the total_length < block_size  we exclude this batch and return an empty dict.\n",
    "        # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.\n",
    "        total_length = (total_length // block_size) * block_size\n",
    "        # Split by chunks of max_len.\n",
    "        result = {\n",
    "            k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n",
    "            for k, t in concatenated_examples.items()\n",
    "        }\n",
    "        result[\"labels\"] = result[\"input_ids\"].copy()\n",
    "        return result\n",
    "\n",
    "    # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder\n",
    "    # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower\n",
    "    # to preprocess.\n",
    "    #\n",
    "    # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:\n",
    "    # https://huggingface.co/docs/datasets/process#map\n",
    "\n",
    "    with training_args.main_process_first(desc=\"grouping texts together\"):\n",
    "        if not data_args.streaming:\n",
    "            lm_datasets = tokenized_datasets.map(\n",
    "                group_texts,\n",
    "                batched=True,\n",
    "                num_proc=data_args.preprocessing_num_workers,\n",
    "                load_from_cache_file=not data_args.overwrite_cache,\n",
    "                desc=f\"Grouping texts in chunks of {block_size}\",\n",
    "            )\n",
    "        else:\n",
    "            lm_datasets = tokenized_datasets.map(\n",
    "                group_texts,\n",
    "                batched=True,\n",
    "            )\n",
    "    lm_datasets.save_to_disk('/root/data/m-a-p/lm_datasets_8K')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c7730593",
   "metadata": {},
   "outputs": [],
   "source": [
    "if data_args.use_tokenizer_data:\n",
    "    lm_datasets=datasets.load_from_disk('/root/data/m-a-p/lm_datasets_8K')\n",
    "    #tokenized_datasets=load_dataset('/root/data/m-a-p/tokenized_datasets')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e332ad5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#train_dataset = lm_datasets['train'].select(range(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "37fef4a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "if training_args.do_train:\n",
    "    # if \"train\" not in tokenized_datasets:\n",
    "    #     raise ValueError(\"--do_train requires a train dataset\")\n",
    "    train_dataset = lm_datasets[\"train\"]\n",
    "    if data_args.max_train_samples is not None:\n",
    "        max_train_samples = min(len(train_dataset), data_args.max_train_samples)\n",
    "        train_dataset = train_dataset.select(range(max_train_samples))\n",
    "\n",
    "if training_args.do_eval:\n",
    "    if \"validation\" not in tokenized_datasets:\n",
    "        raise ValueError(\"--do_eval requires a validation dataset\")\n",
    "    eval_dataset = lm_datasets[\"validation\"]\n",
    "    if data_args.max_eval_samples is not None:\n",
    "        max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)\n",
    "        eval_dataset = eval_dataset.select(range(max_eval_samples))\n",
    "\n",
    "    def preprocess_logits_for_metrics(logits, labels):\n",
    "        if isinstance(logits, tuple):\n",
    "            # Depending on the model and config, logits may contain extra tensors,\n",
    "            # like past_key_values, but logits always come first\n",
    "            logits = logits[0]\n",
    "        return logits.argmax(dim=-1)\n",
    "\n",
    "    metric = evaluate.load(\"accuracy\", cache_dir=model_args.cache_dir)\n",
    "\n",
    "    def compute_metrics(eval_preds):\n",
    "        preds, labels = eval_preds\n",
    "        # preds have the same shape as the labels, after the argmax(-1) has been calculated\n",
    "        # by preprocess_logits_for_metrics but we need to shift the labels\n",
    "        labels = labels[:, 1:].reshape(-1)\n",
    "        preds = preds[:, :-1].reshape(-1)\n",
    "        return metric.compute(predictions=preds, references=labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "daced54c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/root/.conda/envs/xtuner/lib/python3.10/site-packages/accelerate/accelerator.py:436: FutureWarning: Passing the following arguments to `Accelerator` is deprecated and will be removed in version 1.0 of Accelerate: dict_keys(['dispatch_batches']). Please pass an `accelerate.DataLoaderConfiguration` instead: \n",
      "dataloader_config = DataLoaderConfiguration(dispatch_batches=None)\n",
      "  warnings.warn(\n",
      "[INFO|trainer.py:1714] 2024-04-15 21:16:17,013 >> ***** Running training *****\n",
      "[INFO|trainer.py:1715] 2024-04-15 21:16:17,014 >>   Num examples = 182,089\n",
      "[INFO|trainer.py:1716] 2024-04-15 21:16:17,014 >>   Num Epochs = 1\n",
      "[INFO|trainer.py:1717] 2024-04-15 21:16:17,014 >>   Instantaneous batch size per device = 1\n",
      "[INFO|trainer.py:1720] 2024-04-15 21:16:17,015 >>   Total train batch size (w. parallel, distributed & accumulation) = 1\n",
      "[INFO|trainer.py:1721] 2024-04-15 21:16:17,015 >>   Gradient Accumulation steps = 1\n",
      "[INFO|trainer.py:1722] 2024-04-15 21:16:17,015 >>   Total optimization steps = 182,089\n",
      "[INFO|trainer.py:1723] 2024-04-15 21:16:17,067 >>   Number of trainable parameters = 231,625,216\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='522' max='182089' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [   522/182089 05:09 < 30:01:04, 1.68 it/s, Epoch 0.00/1]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>500</td>\n",
       "      <td>8.647800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "# Initialize our Trainer\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=training_args,\n",
    "    train_dataset=train_dataset if training_args.do_train else None,\n",
    "    eval_dataset=eval_dataset if training_args.do_eval else None,\n",
    "    tokenizer=tokenizer,\n",
    "    # Data collator will default to DataCollatorWithPadding, so we change it.\n",
    "    data_collator=default_data_collator,\n",
    "    compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None,\n",
    "    preprocess_logits_for_metrics=preprocess_logits_for_metrics\n",
    "    if training_args.do_eval and not is_torch_tpu_available()\n",
    "    else None,\n",
    ")\n",
    "\n",
    "# Training\n",
    "if training_args.do_train:\n",
    "    checkpoint = None\n",
    "    if training_args.resume_from_checkpoint is not None:\n",
    "        checkpoint = training_args.resume_from_checkpoint\n",
    "    elif last_checkpoint is not None:\n",
    "        checkpoint = last_checkpoint\n",
    "    train_result = trainer.train(resume_from_checkpoint=checkpoint)\n",
    "    trainer.save_model()  # Saves the tokenizer too for easy upload\n",
    "\n",
    "    metrics = train_result.metrics\n",
    "\n",
    "    max_train_samples = (\n",
    "        data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)\n",
    "    )\n",
    "    metrics[\"train_samples\"] = min(max_train_samples, len(train_dataset))\n",
    "\n",
    "    trainer.log_metrics(\"train\", metrics)\n",
    "    trainer.save_metrics(\"train\", metrics)\n",
    "    trainer.save_state()\n",
    "\n",
    "# Evaluation\n",
    "if training_args.do_eval:\n",
    "    logger.info(\"*** Evaluate ***\")\n",
    "\n",
    "    metrics = trainer.evaluate()\n",
    "\n",
    "    max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)\n",
    "    metrics[\"eval_samples\"] = min(max_eval_samples, len(eval_dataset))\n",
    "    try:\n",
    "        perplexity = math.exp(metrics[\"eval_loss\"])\n",
    "    except OverflowError:\n",
    "        perplexity = float(\"inf\")\n",
    "    metrics[\"perplexity\"] = perplexity\n",
    "\n",
    "    trainer.log_metrics(\"eval\", metrics)\n",
    "    trainer.save_metrics(\"eval\", metrics)\n",
    "\n",
    "kwargs = {\"finetuned_from\": model_args.model_name_or_path, \"tasks\": \"text-generation\"}\n",
    "if data_args.dataset_name is not None:\n",
    "    kwargs[\"dataset_tags\"] = data_args.dataset_name\n",
    "    if data_args.dataset_config_name is not None:\n",
    "        kwargs[\"dataset_args\"] = data_args.dataset_config_name\n",
    "        kwargs[\"dataset\"] = f\"{data_args.dataset_name} {data_args.dataset_config_name}\"\n",
    "    else:\n",
    "        kwargs[\"dataset\"] = data_args.dataset_name\n",
    "\n",
    "if training_args.push_to_hub:\n",
    "    trainer.push_to_hub(**kwargs)\n",
    "else:\n",
    "    trainer.create_model_card(**kwargs)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
